<?php

/**
 * Created by PhpStorm.
 * User: lcw-home
 * Date: 2015/11/15
 * Time: 11:23
 */
namespace System\Model;
use Common\AdminModel;
use Common\Lib\Auth;
class UserModel extends  AdminModel
{
    private $userInfo=null;

    public function login($uid){

        $user = $this->field(true)->find($uid);
        if(!$user || 1 != $user['status']) {
            $this->error = '用户不存在或已被禁用！';
            return false;
        }
        //记录行为
        $this->userInfo=$user;
        /* 登录用户 */
        $this->autoLogin($user);
        return true;
    }

    /**
     * 注销当前用户
     * @return void
     */
    public function logout(){
        session('user_auth', null);
        session('user_auth_sign', null);
    }

    /**
     * 自动登录用户
     * @param  integer $user 用户信息数组
     */
    private function autoLogin($uid){
        /* 更新登录信息 */
        $data = array(
            'uid'             => $uid,
            'login'           => array('exp', '`login`+1'),
            'last_login_time' => NOW_TIME,
            'last_login_ip'   => get_client_ip(1),
        );
        M('UserLogin')->save($data);
        if(null==$this->userInfo)
            $uInfo=$this->find($user['uid']);
        $rules=Auth::getByUserFull();
        /* 记录登录SESSION和COOKIES */
        $auth = array(
            'uid'             => $uid,
            'gid'=>$this->userInfo['s_gid'],
            'nickname'        => $this->userInfo['nickname'],
            'last_login_time' => $this->userInfo['last_login_time'],
            'rules'=>$rules
        );
        session('user_auth', $auth);
        session('user_auth_sign', data_auth_sign($auth));

    }

    /**
     * 获得用户基本信息对照数组
     * @return array
     */
    public function getCache(){
        $data=$this->field('id,s_nickname,s_gid')->select();
        $cache=array();
        foreach($data as $d){
            $cache[$d['id']]=$d;
        }
        return $cache;
    }
}